<?php
namespace app\admin\controller;
use x\Xbase;
use x\my\TongLianCash;
class Task extends Xbase{
    public function __construct()
    {
      parent::__construct();
      $ip = ip();
      $data = [
        '127.0.0.1'
      ];
      if(!in_array($ip, $data)){
        //$this->exit('IP has no permissions:'.$ip);
      }
    }
    /**
     * 发放分佣奖
     * 间隔1s
     * @return [type] [description]
     */
    public function sendfenyong(){

        #找出未统计金额的会员
        $rs = $this->db->query("
                select
                    id,s_level,s_tree,s_id,level
                from
                    user
                where
                    user_count_money_date<?
                order by
                    s_level desc,id desc
                limit 10",[date('Ymd')]);
        if (!$rs) $this->exit('10');

      
        foreach ($rs as $val) {
            //普通会员不得分佣将
            if($val["level"] == 0){
                continue;
            }
            //e($val['id']);
            $tree = $val['s_tree'].$val['id'].',%';
            $sub_user = $this->db->query("
                select
                    id
                from
                    user
                where
                    s_level>? and s_tree like '".$tree."'",[$val['s_level']]);
            $sub_ids = [];
            foreach ($sub_user as $sub_val) {
                $sub_ids[] = $sub_val['id'];
            }
            if (!$sub_ids) {
              $data = [];
              $this->db->update("user",['user_count_money_date'=>date('Ymd')],['id=?', [$val['id']]]);
                continue;
            }

            //统计昨日下级返佣，当前下级分佣表总金额
            $sub_count_fanyong = $this->db->query("
                select
                    id,money
                from
                    award_fanyong
                where
                    count_date=? and create_time<? and user_id in(".implode(',',$sub_ids).")",[0,strtotime(date('Ymd 00:00:00'))]);
            $sub_count_fenyong = $this->db->query("select id,real_money from award_fenyong where count_date=? and user_id in(".implode(',',$sub_ids).")",[0]);

            $fanyong_money = 0; $fanyong_ids = [];
            $fenyong_money = 0; $fenyong_ids = [];

            foreach ($sub_count_fanyong as $fanyong_val) {
                $fanyong_money += $fanyong_val['money'];
                $fanyong_ids[] = $fanyong_val['id'];
            }
            foreach ($sub_count_fenyong as $fenyong_val) {
                $fenyong_money += $fenyong_val['award_fenyong'];
                $fenyong_ids[] = $fenyong_val['id'];
            }

            $money = bcadd($fanyong_money,$fenyong_money,2);

            $this->db->begin();
            $mysql = [];

            if ($money>=0.04) { #小于0.01不计

                $per = $val['s_id']==0?3:4;
                $award_fenyong = [
                    'order_no' => com_order_no(),
                    'user_id' => $val['id'],
                    'sub_user_money_fanyong' => $fanyong_money,
                    'sub_user_money_fenyong' => $fenyong_money,
                    's_id'  => $val['s_id'],
                    'money' => $money,
                    'real_money' => bcdiv($money, $per,2),
                    'create_time' => time(),
                    'note' => '获得分佣',
                ];
                $mysql[] = $award_fenyong_id = $this->db->insert('award_fenyong',$award_fenyong);

                if ($fanyong_ids) {
                    $map = [];
                    $map[] = ['and', 'id', 'in', $fanyong_ids];
                    $w = where($map);
                    $mysql[] = $sub_count_fanyong = $this->db->query("update award_fanyong set award_fenyong_id=".$award_fenyong_id.",update_time=".time().",count_date=".date('Ymd')." $w[0]", $w[1]);
                }

                if ($fenyong_ids) {
                    $map = [];
                    $map[] = ['and', 'id', 'in', $fenyong_ids];
                    $w = where($map);
                    $mysql[] = $sub_count_fanyong = $this->db->query("update award_fenyong set award_fenyong_id=".$award_fenyong_id.",update_time=".time().",count_date=".date('Ymd')." $w[0]", $w[1]);
                }
                #bill
                $mysql[] = m('Userbill','xcom')->doit($award_fenyong['order_no'], $award_fenyong['user_id'], 108, 'award_fenyong', $award_fenyong_id,  $award_fenyong['real_money'],'money',$award_fenyong['note']);

            }
            $mysql[] = $this->db->update("user",['user_count_money_date'=>date('Ymd')],['id=?', [$val['id']]]);
            $rs = $this->db->end($mysql);
        }
        $this->exit('1');
    }

    /**
     * 代发轮询
     * @return [type] [description]
     */
    public function daifa(){
        $p= new TongLianCash([
            'user' => c('api.tl_cash_user'),
            'pwd'  => c('api.tl_cash_pwd'),
            'merid'=> c('api.tl_cash_merid'),
            'certFile'=> c('api.tl_cash_certfile'),
            'privateKeyFile'=> c('api.tl_cash_privatekeyfile'),
            'certpwd'=> c('api.tl_cash_certpwd'),
        ]);
        $rs = $this->db->query('select * from withdraw where daifa_status=? and shenhe_status=? and daifa_type=? order by query_nums asc,id asc limit 0,1',[0,2,1]);
        foreach ($rs as $val) {
            $msg=$val['order_no'];
            $r=$p->cash($val['order_no'],$val['bank_username'],$val['bank_no'],bcmul($val['real_money'],100,0));
            if (in_array($r['code'],['0000','1102','1108'])) {
                $msg.="=>成功";
                //请求成功
                $this->db->update('withdraw',['id'=>$val['id'],'daifa_nums'=>0,'daifa_status'=>1]);
            }else{
                $msg.="=>失败";
                $rs = $this->db->update('withdraw',['id'=>$val['id'],'daifa_status'=>3,'daifa_note'=>$msg,'daifa_time'=>time()]);
                m('Log','xcom')->record('0', '代发失败，订单id['.$val["id"].']','admin_user');
                $this->db->update('withdraw',['id'=>$val['id'],'daifa_nums'=>$val['daifa_nums']+1]);
            }
            //e($msg);
        }
        $this->exit('1');
    }

    /**
     * 代发查询
     * @return [type] [description]
     */
    public function daifa_query(){
        $p= new \my\TongLianCash([
            'user' => c('api.tl_cash_user'),
            'pwd'  => c('api.tl_cash_pwd'),
            'merid'=> c('api.tl_cash_merid'),
            'certFile'=> c('api.tl_cash_certfile'),
            'privateKeyFile'=> c('api.tl_cash_privatekeyfile'),
            'certpwd'=> c('api.tl_cash_certpwd'),
        ]);
        $rs = $this->db->query('select * from withdraw where daifa_status=? and shenhe_status=? and daifa_type=? order by query_nums asc,id asc limit 0,1',[1,2,1]);
        foreach ($rs as $val) {
            //e($val['order_no']);
            $r = $p->query($val['order_no']);
            if (in_array($r['code'],['2006','2004','2002','1999','1002','1001','1000','0002','0001','3030','3004','3028'])) {
                //代发失败
                $rs = $this->db->update('withdraw',['id'=>$val['id'],'daifa_status'=>3,'daifa_note'=>'代发失败','daifa_time'=>time()]);
                m('Log','xcom')->record('0', '代发失败，订单id['.$val["id"].']','admin_user');
            }
            if (in_array($r['code'],['0000','4000'])) {
                //代发成功
                $this->db->update('withdraw',['id'=>$val['id'],'status'=>2,'daifa_status'=>2,'daifa_number'=>'','daifa_note'=>$r['msg'],'daifa_time'=>time(),'daifa_data'=>time()]);
                m('Log','xcom')->record('0', '代发成功，订单id['.$val["id"].']','admin_user');

                $data = [
                    "table" => "withdraw",
                    "table_id" => $val['id'],
                    "title" => "代发成功",
                    "content" => "代发成功",
                    "create_time" => time(),
                ];
                $this->db->insert("com_message",$data);
            }
            $this->db->update('withdraw',['id'=>$val['id'],'query_nums'=>$val['query_nums']+1]);
        }
        $this->exit('1');
    }

    /**
     * 统计会员每日财务
     * @return [type] [description]
     */
    public function userReport(){
        $pre_day = date("Ymd",strtotime("-1 day"));
        $rs = $this->db->query("select id from user where user_report_day<? order by id asc limit 1",[$pre_day], 1);
        if (!$rs) {
          $this->exit('10');
        }
        //统计用户 返佣分佣
        //开始事务
        $this->db->begin();
        $mysql=[];
        //返佣
        $rs_fanyong = $this->db->query("select IFNULL(sum(money), 0) as money from award_fanyong where user_id=? and user_report_day=0",[$rs['id']],1);
        //分佣
        $rs_fenyong = $this->db->query("select IFNULL(sum(money), 0) as money from award_fenyong where user_id=? and user_report_day=0",[$rs['id']],1);
        $data = [
            'award_fanyong'=>$rs_fanyong['money'],
            'award_fenyong'=>$rs_fenyong['money'],
            'ymd'=>$pre_day,
            'y'=>date("Y",strtotime("-1 day")),
            'm'=>date("m",strtotime("-1 day")),
            'd'=>date("d",strtotime("-1 day")),
            'user_id'=>$rs['id'],
            'create_time'=>time(),
        ];
        $this->db->query("update award_fanyong set user_report_day=? where user_id=?",[$pre_day,$rs['id']]);
        $this->db->query("update award_fenyong set user_report_day=? where user_id=?",[$pre_day,$rs['id']]);
        $mysql[] = $this->db->insert('user_report',$data);
        //更新
        $mysql[] = $this->db->update('user',['id'=>$rs['id'], 'user_report_day'=>$pre_day]);
        $this->db->end($mysql);
        $this->exit('1');
    }

    public function exit($s='1'){
      exit($s);
      js_url('',$s);
    }
}
